class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k)
    {
        map<string, int> cnt;
        vector<string> ret;
        for (auto& x : words)cnt[x]++;
        for (auto& x : cnt) ret.push_back(x.first);
        auto cmp = [&](string& x, string& y)
            {
                return cnt[x] > cnt[y];
            };
        //map本身已经使string有序,只需保证排序稳定即可
        //还可以使用优先级队列
        stable_sort(ret.begin(), ret.end(), [&](const string& x, const string& y)
            {
                return cnt[x] > cnt[y];
            });

        return vector(ret.begin(), ret.begin() + k);
    }
};